using Avalonia.Controls;
using Avalonia.Interactivity;
using IntegratedMeasuring.ViewModels.Scheme;
using IntegratedMeasuring.Storage;
using IntegratedMeasuring.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using Avalonia.Collections;
using System.Threading.Tasks;
using IntegratedMeasuring.ViewModels.Entity;
using System.ComponentModel;

namespace IntegratedMeasuring.Pages;

public partial class OperationLogPage : UserControl
{
    private List<LogRecord> _allLogs = new();
    private DataGridCollectionView? _logView;

    public OperationLogPage()
    {
        InitializeComponent();
        Loaded += OnLoaded;
    }

    private async void OnLoaded(object? sender, RoutedEventArgs e)
    {
        InitializeLevelComboBox();
        await LoadLogData();
    }

    private void InitializeLevelComboBox()
    {
        LevelComboBox.ItemsSource = new[] { "全部" }.Concat(Enum.GetValues(typeof(ViewModels.Entity.GC.LogLevel)).Cast<IntegratedMeasuring.ViewModels.Entity.GC.LogLevel>().Select(x => x.ToString()));
        LevelComboBox.SelectedIndex = 0;
    }

    private async Task LoadLogData()
    {
        try
        {
            await LoadingHelper.ExecuteWithLoadingAsync(this, async () =>
            {
                _allLogs = await LogDataStorage.Instance.QueryAllAsync<LogRecord>();
                _logView = new DataGridCollectionView(_allLogs);
                LogDataGrid.ItemsSource = _logView;
            }, "加载日志数据中...");
        }
        catch (Exception ex)
        {
            NotificationHelper.ShowError("加载失败", ex.Message);
        }
    }

    private async void SearchButton_Click(object? sender, RoutedEventArgs e)
    {
        try
        {
            await LoadingHelper.ExecuteWithLoadingAsync(this, async () =>
            {
                string levelText = (LevelComboBox.SelectedItem as string) ?? "全部";
                string keyword = KeywordTextBox.Text?.Trim() ?? "";
                DateTime? startDate = StartDatePicker.SelectedDate;
                DateTime? endDate = EndDatePicker.SelectedDate;

                var filtered = _allLogs.Where(log =>
                {
                    // 等级过滤
                    if (levelText != "全部" && log.Level.ToString() != levelText)
                        return false;
                    // 关键字过滤
                    if (!string.IsNullOrEmpty(keyword) && !(log.Title.Contains(keyword, StringComparison.OrdinalIgnoreCase) || log.Content.Contains(keyword, StringComparison.OrdinalIgnoreCase)))
                        return false;
                    // 时间过滤
                    if (startDate.HasValue && log.CreateTime < startDate.Value)
                        return false;
                    if (endDate.HasValue && log.CreateTime > endDate.Value.AddDays(1))
                        return false;
                    return true;
                }).ToList();
                _logView = new DataGridCollectionView(filtered);
                LogDataGrid.ItemsSource = _logView;
            }, "查询中...");
        }
        catch (Exception ex)
        {
            NotificationHelper.ShowError("查询失败", ex.Message);
        }
    }

    private void ExportButton_Click(object? sender, RoutedEventArgs e)
    {
        NotificationHelper.ShowInfo("导出提示", "导出功能暂未实现");
    }

    private async void LogDataGrid_DoubleTapped(object? sender, Avalonia.Input.TappedEventArgs e)
    {
        try
        {
            if (LogDataGrid.SelectedItem is LogRecord log)
            {
                var detailDialog = new LogDetailDialog(log);
                var window = this.VisualRoot as Window;
                await detailDialog.ShowDialog(window);
            }
        }
        catch (Exception ex)
        {
            NotificationHelper.ShowError("显示详情失败", ex.Message);
        }
    }
}
